﻿using System;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Net.Http;

namespace com.sense.cloud.common
{
    class API2Request
    {

        private string appUrl;
        private string appId;
        private string appSecret;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="appUrl">应用地址</param>
        /// <param name="appId">应用Id,如何查看，请</param>
        /// <param name="appSecret"></param>
        public API2Request(string appUrl,string appId,string appSecret)
        {
            this.appUrl = appUrl;
            this.appId = appId;
            this.appSecret = appSecret;
        }

        /// <summary>
        /// 发送请求，并将返回的结果解析成 json 对象
        /// </summary>
        /// <param name="reqUrl">请求地址，如"/v2/sv/addUser"</param>
        /// <param name="reqDataJson">请求体数据，json 对象</param>
        /// <returns>请求结果解析的 json 对象</returns>
        public JObject send(string reqUrl,JObject reqDataJson)
        {
            //将 json 序列化为 json 字符串
            string reqDataStr = JsonConvert.SerializeObject(reqDataJson);
            //构建并发送请求
            string resultStr = buildRequest(reqUrl,reqDataStr);
            //将返回结果解析成 json 对象
            return JObject.Parse(resultStr) ;
        }

        private string buildRequest(string reqUrl, string reqDataStr)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;

            TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
            //一定要加 Math.Round(),否则会出现小数点
            string timestamp = Convert.ToString(Math.Round(ts.TotalSeconds*1000));
            //生成一个随机数
            string nonce = Guid.NewGuid().ToString();

            HttpContent content = new StringContent(reqDataStr);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //一定不能加下面的这一句
            //content.Headers.ContentType.CharSet = "UTF-8";
            content.Headers.Add("SenseAppID", this.appId);
            content.Headers.Add("SenseTimestamp", timestamp);
            content.Headers.Add("SenseNonce", nonce);
            content.Headers.Add("SenseSign", makeSignature(reqUrl, reqDataStr, timestamp, nonce));

            HttpClient client = new HttpClient();
            HttpResponseMessage resultMessage = client.PostAsync(this.appUrl + reqUrl, content).Result;

            return resultMessage.Content.ReadAsStringAsync().Result;

        }

        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="reqUrl">请求地址</param>
        /// <param name="reqData">请求数据</param>
        /// <param name="timestamp">当时时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <returns>签名后的 base64 字符串</returns>
        private string makeSignature(string reqUrl, string reqData,string timestamp,string nonce)
        {

            Encoding UTF8 = Encoding.UTF8;
            byte[] keyBytes = UTF8.GetBytes(this.appSecret);
            byte[] dataBytes = UTF8.GetBytes(timestamp + nonce + reqUrl + reqData);

            using (var hmacsh256 = new HMACSHA256(keyBytes))
            {
                byte[] signByte =hmacsh256.ComputeHash(dataBytes);
                return Convert.ToBase64String(signByte);
            }
        }

    }
}
